import adModel from "../../main/view/adView/adModel";

/**
 * @author 黄学捷
 * @com 网络AJAX请求
 * @timer 2020-12-07
 */
class NetMgrClazz {
    /**
    * @param reType 请求类型 POST或者GET 
    * @param reUrl 请求地址
    * @param obj 请求参数{xx:xx}
    * @param backFun 请求成功回调
    * @param s 作用域 
    * 
    */
    private send(reType: string, reUrl: string, param: any, backFun: Function, s?: any) {
        var hr = new Laya.HttpRequest();
        let apiUrl = reUrl;
        hr.once(Laya.Event.ERROR, this, this.error, [backFun, s, hr]);
        hr.once(Laya.Event.PROGRESS, this, this.onHttpRequestProgress);
        hr.once(Laya.Event.COMPLETE, this, this.success, [backFun, s, hr,reUrl]);
        let toData = param// this.CryptoJSAesEncryptSimple(param)
        // let requestData = ""
        // for (var name in toData) {
        //     requestData += name + '=' + toData[name] + '&';
        // }
        param.k = adModel.initSessionInfo.s;
        // let newParam = ArrayUtils.conleData(toData);
        // let da = CryptoJS POST("sss")
        // console.log("da",da)
        if (reType.toUpperCase() == "POST") {
            hr.send(apiUrl, param, "POST", 'json', ["Content-Type", "application/json"]);
        }
        if (reType.toUpperCase() == "GET") {

            hr.send(apiUrl + "?" + param, null, "GET", 'json', ["Content-Type", "application/json"]);
        }
    }
    /**异步 */
    public async sendAsync(reUrl: string, param: any = {}, reType: string = "POST") {
        return new Promise((res, rej) => {
            this.send(reType, reUrl, param, (data) => {
                res(data)
            })
        })
    }
    /**对数据进行加密处理 */
    private CryptoJSAesEncryptSimple(param, passphrase = "e499a98411a65c3e2bcdcd3f8a2b0669") {
        try {
            let plainText = JSON.stringify(param);
            let salt = CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.random(8));
            let iv = CryptoJS.lib.WordArray.random(16) as any;
            let key = CryptoJS.MD5(passphrase + '_' + salt) as any;
            let encrypted = CryptoJS.AES.encrypt(plainText, key, { iv: iv });
            return {
                c: CryptoJS.enc.Base64.stringify(encrypted.ciphertext),
                s: salt,
                i: CryptoJS.enc.Hex.stringify(iv)
            };
        } catch (e) {
            console.error('获取参数错误', e);
            return {};
        }
    }
    // 设置登录态
    private matchRes = [];
    private success(backFun, s, hr,apiUrl) {
        if(apiUrl.indexOf(ZYAPI.LOGIN)!=-1){
            this.matchRes = this.getHeader(hr, 'Set-Cookie').match(/PHPSESSID=(.*)?;/i) ||[];
            adModel.initSessionInfo.s = this.matchRes[1]
        }
        if (typeof backFun == "function") {
            backFun.call(s, hr.data)
        }
       
    }
    private onHttpRequestProgress() {

    }
    private error(backFun, s, hr) {
        console.log("请求错误", s, hr);
        if (typeof backFun == "function") {
            backFun.call(s, { code: 1, msg: "error", data: hr.data })
        }
    }
    private getHeader(header, name) {
        if(header){
            return header.http.getAllResponseHeaders()
        }
        return '';
    }
    getIndexOfs = function (arr, obj) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] === obj) {
                return i;
            }
        }
        return -1;
    }
}
export const ZYNet = new NetMgrClazz()